# 封装数据库
import pymysql


class DBUtil:
    conn = None

    # 封装数据库连接的方法
    @classmethod
    def __connect_db(cls):
        cls.conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                                   database="ihrm", charset="utf8")
        return cls.conn

    # 封装数据库关闭的方法
    @classmethod
    def __close_db(cls):
        cls.conn.close()

    # 数据库的查询
    # 加上装饰器是为了掉哦那个方调用方便
    @classmethod
    def query_db(cls, sql):
        cursor = None
        result = None
        try:
            # 创建数据库连接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # 执行sql，返回结果
            cursor.execute(sql)
            result = cursor.fetchone()
        except Exception as err:
            print("错误提示信息：", err)
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_db()
        return result

    @classmethod
    def uil(cls, sql):
        cursor = None
        try:
            # 创建数据库连接
            cls.conn = cls.__connect_db()
            # 获取游标
            cursor = cls.conn.cursor()
            # sqly语句
            cursor.execute(sql)
            # 打印影响行
            affect_row = cls.conn.affected_rows()
            print("啊啊啊啊", affect_row)
            # 执行\回滚
            cls.conn.commit()
        except Exception as err:
            print("错误提示：", err)
            cls.conn.rollback()
        finally:
            # 关闭游标
            cursor.close()
            # 关闭连接
            cls.__close_db()


if __name__ == '__main__':
    # print(DBUtil.query_db("select * from t_book;"))
    DBUtil.uil("update t_book set `read`=`read`+2 where id=13")
